#include "napi/native_api.h"
#include "ark_runtime/jsvm.h"
#include <hilog/log.h>
#include <string>

static int g_aa = 0;
static JSVM_CallbackStruct param[] = {};
static JSVM_PropertyDescriptor descriptor[] = {};

JSVM_Env env;
JSVM_VM vm;
JSVM_VMScope vmScope;
JSVM_EnvScope envScope;
JSVM_HandleScope handleScope;

/**
 * 获取 ets 传过来的字符串参数
 * @param env
 * @param info
 * @return
 */
std::string getCodeString(napi_env env, napi_callback_info info) {
    size_t argc = 1;
    napi_value argv[1] = {nullptr};
    napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
    std::string jsCodeStr;
    size_t result = 0;
    napi_get_value_string_utf8(env, argv[0], nullptr, NAPI_AUTO_LENGTH, &result);
    const size_t bufSize = result + 1;
    char *buf = new char[bufSize];
    napi_status status = napi_get_value_string_utf8(env, argv[0], buf, bufSize, &result);
    if (status == napi_ok) {
        jsCodeStr = buf;
    }
    free(buf);
    return jsCodeStr;
}

/**
 *  javascript代码执行失败的处理
 * @param nEnv
 * @param env
 * @param res
 */
void RunScriptFail(napi_env &nEnv, JSVM_Env &env, JSVM_Status &res) {
    JSVM_Value exceptionValue;
    JSVM_Status status = OH_JSVM_GetAndClearLastException(env, &exceptionValue);
    if (status == JSVM_OK) {
        JSVM_Value message;
        OH_JSVM_GetNamedProperty(env, exceptionValue, "message", &message);
        size_t length;
        OH_JSVM_GetValueStringUtf8(env, message, nullptr, 0, &length);
        char *buffer = new char[length + 1];
        OH_JSVM_GetValueStringUtf8(env, message, buffer, length + 1, nullptr);
        napi_throw_error(nEnv, std::to_string(static_cast<int>(status)).c_str(), buffer);
        delete[] buffer;
    } else {
        napi_throw_error(nEnv, std::to_string(static_cast<int>(status)).c_str(), nullptr);
        OH_LOG_INFO(LOG_APP, "JSVM RunJsVm failed Error code:  %{public}d", static_cast<int>(res));
    }
}

/**
 * 开始 JSVM 虚拟机
 */
static napi_value InitJsVm(napi_env nEnv, napi_callback_info nInfo) {
    // 配置
    JSVM_InitOptions initOptions;
    memset(&initOptions, 0, sizeof(initOptions));
    initOptions.externalReferences = nullptr;
    if (g_aa == 0) {
        g_aa++;
        // 初始化JavaScript引擎实例
        OH_JSVM_Init(&initOptions);
    }
    // 创建环境
    JSVM_CreateVMOptions options;
    memset(&options, 0, sizeof(options));
    OH_JSVM_CreateVM(&options, &vm);
    OH_JSVM_OpenVMScope(vm, &vmScope);
    OH_JSVM_CreateEnv(vm, sizeof(descriptor) / sizeof(descriptor[0]), descriptor, &env);
    OH_JSVM_OpenEnvScope(env, &envScope);
    OH_JSVM_OpenHandleScope(env, &handleScope);
    return nullptr;
}

/**
 * 停止 JSVM 虚拟机
 * TODO 实际测试无效
 */
static napi_value CloseJsVm(napi_env nEnv, napi_callback_info nInfo) {
    OH_JSVM_CloseHandleScope(env, handleScope);
    OH_JSVM_CloseEnvScope(env, envScope);
    OH_JSVM_CloseVMScope(vm, vmScope);
    OH_JSVM_DestroyEnv(env);
    OH_JSVM_DestroyVM(vm);
    return nullptr;
}

/**
 * 执行 js 代码
 * @param nEnv
 * @param nInfo
 * @return
 */
static napi_value RunJsVm(napi_env nEnv, napi_callback_info nInfo) {
    std::string sourceCodeStr = getCodeString(nEnv, nInfo);
    napi_value nResult = nullptr;
    JSVM_Value jsVmResult;
    if (strcmp(sourceCodeStr.c_str(), "defineClass") == 0) {
         OH_LOG_INFO(LOG_APP, "JSVM API DefineClass called");
    } else {
        JSVM_Value sourceCodeValue = nullptr;
        OH_JSVM_CreateStringUtf8(env, sourceCodeStr.c_str(), sourceCodeStr.size(), &sourceCodeValue);
        JSVM_Script script;
        // 编译JavaScript代码字符串并返回编译后的脚本
        OH_JSVM_CompileScript(env, sourceCodeValue, nullptr, 0, true, nullptr, &script);
        // 执行JavaScript代码字符串
        JSVM_Status res = OH_JSVM_RunScript(env, script, &jsVmResult);
        if (res != JSVM_OK) {
            RunScriptFail(nEnv, env, res);
            napi_get_null(nEnv, &nResult);
        } else {
            JSVM_ValueType valueType;
            OH_JSVM_Typeof(env, jsVmResult, &valueType);
            if (valueType == JSVM_STRING) {
                constexpr size_t PREALLOC_SIZE = 256;
                char preallocMemory[PREALLOC_SIZE];
                char *buff = preallocMemory;
                // 获取长度
                size_t totalLen = 0;
                OH_JSVM_GetValueStringUtf8(env, jsVmResult, nullptr, 0, &totalLen);
                size_t needed = totalLen + 1;
                if (needed > PREALLOC_SIZE) {
                    // 分配空间，大小需包含终止字符
                    buff = new char[needed];
                }
                // 获取字符串
                OH_JSVM_GetValueStringUtf8(env, jsVmResult, buff, needed, nullptr);
                napi_create_string_utf8(nEnv, buff, totalLen, &nResult);
            }   
            else {
                OH_LOG_INFO(LOG_APP, "JSVM result type not string");
            }
        }
    }
    return nResult;
}


static napi_value Add(napi_env env, napi_callback_info info)
{
    size_t argc = 2;
    napi_value args[2] = {nullptr};

    napi_get_cb_info(env, info, &argc, args , nullptr, nullptr);

    napi_valuetype valuetype0;
    napi_typeof(env, args[0], &valuetype0);

    napi_valuetype valuetype1;
    napi_typeof(env, args[1], &valuetype1);

    double value0;
    napi_get_value_double(env, args[0], &value0);

    double value1;
    napi_get_value_double(env, args[1], &value1);

    napi_value sum;
    napi_create_double(env, value0 + value1, &sum);

    return sum;

}

EXTERN_C_START
static napi_value Init(napi_env env, napi_value exports)
{
    napi_property_descriptor desc[] = {
        { "add", nullptr, Add, nullptr, nullptr, nullptr, napi_default, nullptr },
        {"runJsVm", nullptr, RunJsVm, nullptr, nullptr, nullptr, napi_default, nullptr},
        {"initJsVm", nullptr, InitJsVm, nullptr, nullptr, nullptr, napi_default, nullptr},
        {"closeJsVm", nullptr, CloseJsVm, nullptr, nullptr, nullptr, napi_default, nullptr},
    };
    napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
    return exports;
}
EXTERN_C_END

static napi_module demoModule = {
    .nm_version = 1,
    .nm_flags = 0,
    .nm_filename = nullptr,
    .nm_register_func = Init,
    .nm_modname = "entry",
    .nm_priv = ((void*)0),
    .reserved = { 0 },
};

extern "C" __attribute__((constructor)) void RegisterEntryModule(void)
{
    napi_module_register(&demoModule);
}
